package com.iemes.controller.workcenter_model;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.ItemBomFormMap;
import com.iemes.entity.ItemBomRelationFormMap;
import com.iemes.entity.ItemFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.WorkcenterModel.WorkResourceMapper;
import com.iemes.service.workcenter_model.ItemBomService;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;

/**
 * 
 */
@Controller
@RequestMapping("/workcenter_model/item_bom/")
public class ItemBomController extends BaseController {
	
	@Inject
	private WorkResourceMapper workResourceMapper;
	
	@Inject
	private ItemBomService itemBomService;
	
	private Logger log = Logger.getLogger(this.getClass());
	private String itemBomMaintenanceUrl = Common.BACKGROUND_PATH + "/workcenter_model/item_bom/item_bom_maintenance";
	private String uDefinedDataType = "item_bom_maintenance";

	//页面跳转
	@RequestMapping("item_bom_maintenance")
	public String Get_item_bom_maintenance_Url(Model model,HttpServletRequest request) throws Exception {
		model.addAttribute("res", findByRes());
		model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
		handlePageRes(model,request);
		return itemBomMaintenanceUrl;
	}
	
	/**
	 * 保存物料清单
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveItemBom")
	@SystemLog(module="物料清单维护",methods="物料清单维护-保存物料清单")		//凡需要处理业务逻辑的.都需要记录操作日志
	public String saveItemBom() {
		ItemBomFormMap itemBomFormMap = getFormMap(ItemBomFormMap.class);
		itemBomFormMap.put("create_time", DateUtils.getStringDateTime());
		itemBomFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
		itemBomFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		
		try {
			itemBomService.saveItemBom(itemBomFormMap);	
		} catch (BusinessException e) {
			log.error(e.getMessage());
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText();
	}
	

	/**
	 * 检索物料清单
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("queryItemBom")
	public String queryItemBom(Model model, HttpServletRequest request) {
		String siteId = ShiroSecurityHelper.getSiteId();
		String itemBomNo = request.getParameter("item_bom_no");
		String version = request.getParameter("version");
		//1.查询物料清单基本信息
		ItemBomFormMap itemBomFormMap = new ItemBomFormMap();
		itemBomFormMap.put("item_bom_no", itemBomNo);
		if (!StringUtils.isEmpty(version)) {
			itemBomFormMap.put("item_bom_version", version);
		}
		itemBomFormMap.put("site_id", siteId);
		List<ItemBomFormMap> listItemBomFormMap = baseMapper.findByNames(itemBomFormMap);
		if (!ListUtils.isNotNull(listItemBomFormMap)) {
			String errMessage = "未检索到物料BOM编号为：" + itemBomNo.toUpperCase() + "的信息";
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
			model.addAttribute("errorMessage", errMessage);
			handlePageRes(model,request);
			return itemBomMaintenanceUrl;
		}
		
		itemBomFormMap = listItemBomFormMap.get(0);	
		model.addAttribute("itemBomFormMap", itemBomFormMap);
		
		String ItemBomId = itemBomFormMap.getStr("id");
		//2.查询子物料列表
		ItemBomRelationFormMap itemBomRelationFormMap = new ItemBomRelationFormMap();
		itemBomRelationFormMap.put("item_bom_id", ItemBomId);
		itemBomRelationFormMap.put("orderby"," order by item_seq");
		List<ItemBomRelationFormMap> listItemBomRelationFormMap = new ArrayList<>();
		listItemBomRelationFormMap = baseMapper.findByNames(itemBomRelationFormMap);
		
		//2.2如果有子物料，再查询子物料的详细信息
		if(ListUtils.isNotNull(listItemBomRelationFormMap)) {
			for (int i=0;i<listItemBomRelationFormMap.size();i++) {
				ItemBomRelationFormMap map = listItemBomRelationFormMap.get(i);
				String childItemId = map.getStr("item_id");
				
				List<ItemFormMap> listChildItem = baseMapper.findByAttribute("id", childItemId, ItemFormMap.class);
				if (!ListUtils.isNotNull(listChildItem)) {
					log.error("未查询到子物料的物料信息，请确定该信息是否错误或被删除！");
					model.addAttribute("errorMessage", "未查询到子物料的物料信息，请确定该信息是否错误或被删除！");
					handlePageRes(model,request);
					return itemBomMaintenanceUrl;
				}
				
				map.put("item_no", listChildItem.get(0).getStr("item_no"));
				map.put("item_version", listChildItem.get(0).getStr("item_version"));
				//动态表格里动态控件的ID绑定
				String itemSeq = listChildItem.get(0).getStr("item_seq");				
				map.put("itemCellId1", "itemCellId1_" + itemSeq);
				map.put("itemCellId2", "itemCellId2_" + itemSeq);
				map.put("itemVersionCellId", "versionCellId_" + itemSeq);	
			}
		}
		model.addAttribute("dataBomItems", listItemBomRelationFormMap);

        //3.查询自定义数据
		getUDefinedDataValue(model,ItemBomId,uDefinedDataType,"dataKeys");
		
		model.addAttribute("successMessage", "检索成功");
		handlePageRes(model,request);
		return itemBomMaintenanceUrl;
	}
	
	/**
	 * 删除物料清单
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("delItemBom")
	public String delItemBom(Model model, HttpServletRequest request) {
		String itemBomId = request.getParameter("item_bom_id");
		try {
			if (StringUtils.isEmpty(itemBomId)) {
				throw new BusinessException("操作失败，参数不能为空！");
			}
			itemBomService.delItemBom(itemBomId);
		} catch (BusinessException e) {
			String errMessage = e.getMessage();
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
			model.addAttribute("errorMessage", errMessage);
			handlePageRes(model,request);
			return itemBomMaintenanceUrl;
		}
		model.addAttribute("res", findByRes());
		model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
		model.addAttribute("successMessage", "删除物料清单成功");
		handlePageRes(model,request);
		return itemBomMaintenanceUrl;
	}

}